import { useState, useEffect } from "react";
import { Layout, Select, Menu, Tabs, Table, Input, Button, message } from "antd";
import { request } from "../utils/requset";

const { Content, Sider } = Layout;
const { Option } = Select;
const { TextArea } = Input;

export default function SQLEditPage() {
    const [type, setType] = useState("");
  const [objects, setObjects] = useState([]);
  const [objectType, setObjectType] = useState([]);
  const [selectedObject, setSelectedObject] = useState(null);
  const [objectInfo, setObjectInfo] = useState(null);
  const [viewCode, setViewCode] = useState("");
  const [SQLResult, setSQLResult] = useState(true); 
  const [SQLResultMessage, setSQLResultMessage] = useState(''); 

  useEffect(() => {
    request.get(`/sql/objects?type=${type}`)
    .then(response => {
        setObjects(response.data);
    });
    request.get(`/sql/objects/type`)
    .then(response => {
      setObjectType(response.data.rows);
      if (type==="") {
        setType(response.data.rows[0].table_type);
      };
    });
    
  }, [type]);

  const fetchObjectInfo = (name) => {
    request.get(`/sql/object_info?name=${name}`)
      .then(response => {
        setObjectInfo(response.data);
        setViewCode(response.data.view_code!=="" ? response.data.view_code : "");
      });
  };

  const executeQuery = async () => {
    console.log(viewCode.replace(/\s+/g, "").toUpperCase());
    if (!viewCode.replace(/\s+/g, "").toUpperCase().startsWith('CREATEORREPLACEVIEW') && !viewCode.replace(/\s+/g, "").toUpperCase().startsWith('CREATEVIEW')) {
      message.error("请输入正确视图语句！");
      return;
    }

    try {
      const response = await request.post("/sql/query", {
        sql: viewCode, // 使用选中的文本
        page_size: '100',
      });

      if (response.data.error) {
        setSQLResult(false);
        setSQLResultMessage(response.data.error);
      } else {
        setSQLResult(true);
        setSQLResultMessage('编译成功');
      }
    } catch (error) {
      message.error("编译失败：" + error.message);
    }
  };

  function typeChange(value) {
    setType(value);
    setSelectedObject(null); // 确保切换模式时清除Menu的选中
  }


  return (
    <Layout style={{ minHeight: "calc(100vh - 96px)" }}>
      <Sider width={250} style={{ background: "#fff" }}>
        <Select value={type} onChange={typeChange} style={{ width: "80%", marginLeft: "9px" }}>
          {objectType.map(object => (
            <Option key={object.table_type} value={object.table_type}>{object.table_type}</Option>
          ))}
        </Select>
        <Menu onClick={(e) => { 
            setSelectedObject(e.key);
            fetchObjectInfo(e.key);
        }}>
          {objects.map(obj => (
            <Menu.Item key={obj}>{obj}</Menu.Item>
          ))}
        </Menu>
      </Sider>
      <Content style={{ padding: "0 16px 0 16px", background: "#fff" }}>
        {selectedObject && (
          <Tabs defaultActiveKey="columns">
            <Tabs.TabPane tab="Columns" key="columns">
              <Table dataSource={objectInfo?.columns} columns={[{ title: "Column", dataIndex: 0 },{ title: "Type", dataIndex: 1 },{ title: "Nullable", dataIndex: 2 },{ title: "key", dataIndex: 3 },{ title: "Default", dataIndex: 4 }]} />
            </Tabs.TabPane>
            <Tabs.TabPane tab="Data" key="data">
              <Table dataSource={objectInfo?.data} columns={objectInfo?.columns?.map(col => ({ title: col[0], dataIndex: col[0] }))} />
            </Tabs.TabPane>
            {type === "VIEW" && (
              <Tabs.TabPane tab="SQL Code" key="code">
                <Button type="primary" onClick={executeQuery} style={{ marginBottom: 5 }}>编译</Button>
                <div style={{ color: SQLResult ? 'green' : 'red', marginBottom: 5 }}>
                  {SQLResultMessage}
                </div>
                <TextArea rows={30} language="sql" value={viewCode} onChange={(e => setViewCode(e.target.value))} />
              </Tabs.TabPane>
            )}
          </Tabs>
        )}
      </Content>
    </Layout>
  )
}